<?php
/**
 * Copyright (c) 2016.  hangzhou BOYE .Co.Ltd. All rights reserved
 */

/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2016-12-19
 * Time: 18:39
 */

namespace app\admin\controller;


use app\src\account\enmu\AccountEnmu;
use app\src\accountScore\action\AccountScoreAction;
use app\src\accountScore\logic\AccountScoreHistoryLogic;
use app\src\accountScore\logic\AccountScoreLogic;
use app\src\admin\api\UserApi;
use app\src\admin\helper\AdminFunctionHelper;
use app\src\base\enum\StatusEnum;
use app\src\buyorder\logic\BuyOrderLogic;
use app\src\goods\logic\ProductLogic;
use app\src\powersystem\logic\AuthGroupAccessLogic;
use app\src\powersystem\logic\AuthGroupLogic;
use app\src\scoreEditApply\logic\ScoreEditApplyLogic;
use app\src\scoreEditApply\model\scoreEditApply;
use app\src\session\logic\LoginSessionLogic;
use app\src\user\action\RegisterAction;
use app\src\user\action\RelationAction;
use app\src\user\action\UserLogoutAction;
use app\src\user\logic\MemberConfigLogic;
use app\src\user\logic\MemberLogic;
use app\src\user\logic\UcenterMemberLogic;
use app\src\user\logic\UserGroupLogic;
use app\src\user\logic\UserMemberLogic;
use app\src\user\logic\UserRelationLogic;
use app\src\user\logic\VUserInfoLogic;
use app\src\wallet\logic\WalletHisLogicV2;
use app\src\wallet\logic\WalletLogic;
use think\Db;
use think\Request;

class Member extends Admin
{

    public function index() {

        $mobile   = $this->_param('mobile', '');
        $nickname   = $this->_param('nickname', '');
        $user_group   = $this->_param('user_group', '');
        $params     = [];
        $map        = null;
        if(!empty($user_group)){
            $map['um.group_id'] = $user_group;
            $params['user_group'] = $user_group;
        }
        if(!empty($mobile)){
            $map['mobile'] = array('like', "%" . $mobile  . "%");
            $params['mobile'] = $mobile;
        }
        if(!empty($nickname)){
            $map['nickname'] = array('like', "%" . $nickname  . "%");
            $params['nickname'] = $nickname;
        }

        $p = $this->_param('p',0);
        $page = array('curpage' => $p, 'size' => 10);
        $order = " reg_time desc ";


        $result = (new VUserInfoLogic())->queryWithPagingHtml($map, $page, $order,$params);


        if ($result['status']) {
            $list = [];
            foreach ($result['info']['list'] as $user){
                $score = (new AccountScoreLogic)->getScore(AccountEnmu::USER, $user['id']);
                $user['score'] = ($score['info']['score1']/100).'元';
                $list[] = $user;
            }
            $params['p'] = $p;
            $this -> assign('params',$params);
            $this -> assign('mobile',$mobile);
            $this -> assign("group",$user_group);
            $this -> assign("nickname",$nickname);
            $this -> assign("show", $result['info']['show']);
            $this -> assign("list", $list);
            $result = (new AuthGroupLogic())->queryNoPaging();

            if($result['status']){
                $this->assign('group_info',$result['info']);
            }

            return $this -> boye_display();
        } else {
            $this -> error($result['info']);
        }
    }

    public function vuser() {

        $mobile   = $this->_param('mobile', '');
        $nickname   = $this->_param('nickname', '');
        $map        = null;
        if(!empty($mobile)){
            $map['mobile'] = array('like', "%" . $mobile  . "%");
        }
        if(!empty($nickname)){
            $map['nickname'] = array('like', "%" . $nickname  . "%");
        }

        $p = $this->_param('p',0);
        $page = array('curpage' => $p, 'size' => 10);
        $order = " score1 desc ";


        $result = (new VUserInfoLogic())->queryWithPagingHtml2($map, $page, $order);

        $info = $result['info'];
        if ($result['status']) {
            $this->success('用户获取数据成功', null, $info);
        } else {
            $this->error('用户数据数据失败', null, $result['info']);
        }
    }

    public function score() {

        $account_id  = $this->_param('account_id', '');
        $type  = $this->_param('type', '');

        $p = $this->_param('p', '');
        $size = $this->_param('size', '');
        $order = 'create_time desc';
        $map['type'] = $type;
        $map['account_id'] = $account_id;
        $map['score_type'] = 1;

        $result = (new AccountScoreHistoryLogic())->queryWithPagingHtml($map,['curpage'=>$p,'size'=>$size],$order);
        $count =  (new AccountScoreHistoryLogic())->count($map);

        if($result['status']){
            $info = ['count'=>$count['info'],'list'=>$result['info']['list']];
            $this->success('获取数据成功', null, $info);
        }else{
            $this->error('数据数据失败', null, $result['info']);
        }

    }

    /**
     * 实名审核
     */
    public function realname(){
        $uid = $this->_param('uid',0);
        $this->assign('uid',$uid);
        if($uid >0 ){
            $r = (new MemberLogic())->getInfo(['uid'=>$uid]);

            if(!$r['status']) $this->error($r['info']);
            if(empty($r['info'])) $this->error('uid错误');
            $nickname = $r['info']['nickname'];
        }else{
            $nickname = '';
        }
        $this->assign('nickname',$nickname);
        $page = array('curpage' => $this->_param('p'), 'size' => 15);
        $map  = array('identity_validate'=>2);
        $result = (new MemberConfigLogic())->queryWithPagingHtml($map,$page);
        $this->assign('member',$result['info']['list']);
        $this->assign('show',$result['info']['show']);

        return $this->boye_display();
    }

    /**
     * 审核通过
     */
    public function pass(){

        $map = array('uid' => $this->_param('id',0));
        $entity = array('identity_validate'=>1);
        $result = (new MemberConfigLogic())->save($map,$entity);
        if($result['status']){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }



    /**
     * 审核失败
     */
    public function fail(){
        $map = array('uid'=>$this->_param('id',0));
        $entity = array('identity_validate'=>0);
        $result = (new MemberConfigLogic())->save($map,$entity);

        if($result['status']){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 删除用户
     * 假删除
     */
    public function delete(){
        $uid = $this->_param('uid',0);
        if(AdminFunctionHelper::isRoot($uid)){
            $this->error("禁止对超级管理员进行删除操作！");
        }
        if($uid > 0){
            $result = (new UcenterMemberLogic())->saveByID($uid,['status'=>StatusEnum::DELETE]);
            if(!$result['status']){
                $this->error($result['info']);
            }
        }

        $this->success("删除成功!");
    }

    /**
     * 启用
     */
    public function enable(){
        $id = $this->_param('id',0);
        if(AdminFunctionHelper::isRoot($id)){
            $this->error("禁止对超级管理员进行禁用操作！");
        }

        $result = (new UcenterMemberLogic())->saveByID($id,['status'=>StatusEnum::NORMAL]);
        if($result['status']){
            $this->success('启用成功',url('Admin/Member/index'));
        }else{
            $this->error('启用失败',url('Admin/Member/index'));
        }
    }

    /**
     * 禁用
     */
    public function disable(){

        $id = $this->_param('id',0);
        if(AdminFunctionHelper::isRoot($id)){
            $this->error("禁止对超级管理员进行禁用操作！");
        }

        $result = (new UcenterMemberLogic())->saveByID($id,['status'=>StatusEnum::DISABLED]);
        if($result['status']){
            $this->success('禁用成功',url('Admin/Member/index'));
        }else{
            $this->error('禁用失败',url('Admin/Member/index'));
        }
    }

    /**
     * add
     * @param string $username
     * @param string $password
     * @param string $repassword
     * @return mixed
     */
    public function add($username = '', $password = '', $repassword = ''){
        if(IS_POST){

            if($password != $repassword){
                $this->error("密码和重复密码不一致！");
            }

            $nickname = $this->_param('nickname','');
            $email = $this->_param('email','');

            /* 调用注册接口注册用户 */
            $country = "+86";
            $result = UserApi::register($nickname,$username,$password,$email,$country,"itboye");

            if($result['status']){
                //注册成功
                $this->success('用户添加成功！',url('Member/index'));
            } else { //注册失败，显示错误信息
                $this->error($result['info']);
            }

        }else{

            return $this->boye_display();
        }
    }

    /**
     * 检测用户名是否已存在
     */
    public function check_username($username){
        $result = (new UcenterMemberLogic())->checkUsername($username);
        if($result['status']){
            echo "false";
        }else{
            echo "true";
        }
    }

    /**
     * ajax - member-select
     */
    public function select(){

        $map['nickname'] = array('like', "%" . $this->_param('q', '', 'trim') . "%");
        //$map['nickname'] = array('like', "%" . $q = $this->_param('q',-1)  . "%");

        $q = $this->_param('q',-1);
        if(!empty($q) && $q != -1&&is_numeric($q)){
            $map = [];
            $map['uid'] = $q;
        }

        $page = array('curpage'=>0,'size'=>20);
        $order = "uid desc";
        $result = (new MemberLogic())->query($map,$page, $order,false,'uid,nickname,head');

        if($result['status']){
            $list = $result['info']['list'];
            foreach($list as $key=>$g){
                $list[$key]['id']=$list[$key]['uid'];
                $list[$key]['head'] = getImgUrl($list[$key]['head'],60);
            }

            $this->success("读取成功","",$list);
        }

    }

    public function view(){
        $id = $this->_param('id',0);

        // 1. 基本信息
        $result = (new VUserInfoLogic())->getInfo(array("id"=>$id));
        if(!$result['status']){
            $this->error($result['info']);
        }
        $this->assign("userinfo",$result['info']);
        // 2.用户角色
        $result = (new AuthGroupAccessLogic())->queryGroupInfo($id);
        if(!$result['status']){
            $this->error($result['info']);
        }
        $this->assign("userroles",$result['info']);
        // 3.登陆信息
        $result = (new LoginSessionLogic())->getInfo(['uid'=>$id]);
        if(!$result['status']){
            $this->error($result['info']);
        }

        return $this->boye_display();
    }

    /**
     * 单个用户角色管理
     */
    public function user_role(){

        $id = $this->_param('id','','缺失id');
        if(IS_GET){

            $result = (new AuthGroupAccessLogic())->queryGroupInfo($id);
            $role_ids = "";
            foreach ($result['info'] as $vo){
                $role_ids .= $vo['id'].',';
            }
            $this->assign('role_ids',$role_ids);
            $result = (new AuthGroupLogic())->queryNoPaging();
            $this->assign('roles',$result['info']);
            $this->assign('id',$id);
            return $this->boye_display();
        }else{
            $roles = $this->_param('roles/a',[]);

            $result = (new AuthGroupAccessLogic())->delete(['uid'=>$id]);
            $data = [];
            foreach ($roles as $vo){
                $data[] = ['uid'=>$id,'group_id'=>$vo,'is_auth'=>0];
            }

            $result = (new AuthGroupAccessLogic())->saveAll($data);
            if($result['status']){
                $this->success('保存成功',url("Member/user_role",array('id'=>$id)));
            }else{
                $this->error('保存失败',url("Member/user_role",array('id'=>$id)));
            }
        }

    }

    /**
     * 强制踢下线
     *
     */
    public function force_logout(){
        $id = $this->_param('id','');
        $result = (new UserLogoutAction())->logout($id,"force_logout");

        if($result['status']){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }


    /**
     * 用户编辑
     * @return mixed
     */
    public function edit(){
        $id = $this->_param('id',0);
        if(IS_GET){
            $result = (new VUserInfoLogic())->getInfo(['id'=>$id]);
            $this->assign('user',$result['info']);
            return $this->boye_display();
        }
        $params = Request::instance()->param();
        $params['s_id'] = "itboye";
        $params['uid'] = $id;
        $result = (new UserApi())->update($params);

        if($result['status']){
            $this->success('操作成功',url('Member/edit',array('id'=>$id)));
        }else{
            $this->error('操作失败-'.$result['info'],url('Member/edit',array('id'=>$id)));
        }
    }

    /**
     * 根据手机号查找用户
     */
    public function searchUser() {
        if(IS_AJAX){
//            if(!$this->isBackAdmin()){
//                $this->error('没有权限查看此内容');
//            }

            $mobile = $this->_param('mobile', '');
            if(empty($mobile)) $this->error('mobile 缺失');

            $map = [
                'mobile|nickname' => $mobile
            ];
            $result = (new VUserInfoLogic)->getInfo($map);
            if($result['status']){
                if(empty($result['info'])){
                    $this->error('查找用户失败', null, '没有该用户');
                }
                $info = $result['info'];

                //查找积分
                $result = (new AccountScoreLogic)->getScore(AccountEnmu::USER, $info['id']);
                if(!$result['status']) $this->error('查找用户失败', null, $result['info']);

                $user_info = [
                    'id' => $info['id'],
                    'mobile' => $info['mobile'],
                    'nickname' => $info['nickname'],
                    'score' => $result['info']['score1']
                ];
                $this->success('查找用户成功', null, $user_info);
            }else{
                $this->error('查找用户失败', null, $result['info']);
            }
        }
    }

    /**
     * 修改用户积分
     */
    public function changeScore() {
        if(IS_AJAX){
//            if(!$this->isBackAdmin()){
//                $this->error('没有权限查看此内容');
//            }

            $uid = $this->_param('uid', '');
            $type = $this->_param('type', '');
            $number = floatval($this->_param('number', '')) * 100;

            if(empty($uid)) $this->error('uid 缺失');
            if(!in_array($type, ['plus', 'minus'])) $this->error('error type');
            if($number <= 0) $this->error('修改积分必须大于0');

            if($type == 'plus'){
                $result = (new AccountScoreLogic)->plusScore(AccountEnmu::USER, $uid, AccountScoreLogic::SCORE_TYPE_1, $number, '后台添加积分');
            }else{
                $result = (new AccountScoreLogic)->minusScore(AccountEnmu::USER, $uid, AccountScoreLogic::SCORE_TYPE_1, $number, '后台减少积分');
            }

            if($result['status']){
                $this->success('积分修改成功', null, $result['info']);
            }else{
                $this->error('积分修改失败', null, $result['info']);
            }

        }
    }

    /**
     * 修改用户积分申请
     */
    public function changeScoreApply() {
        if(IS_AJAX){
//            if(!$this->isBackAdmin()){
//                $this->error('没有权限查看此内容');
//            }

            $uid = $this->_param('uid', '');
            $type = $this->_param('type', '');
            $number = floatval($this->_param('number', '')) * 100;

            if(empty($uid)) $this->error('uid 缺失');
            if(!in_array($type, ['plus', 'minus'])) $this->error('error type');
            if($number <= 0) $this->error('修改积分必须大于0');

                $result = (new ScoreEditApplyLogic())->add(['uid'=>$uid,'score_type'=>$type,'number'=>$number]);


            if($result['status']){
                $this->success('积分修改申请提交成功', null, $result['info']);
            }else{
                $this->error('积分修改申请提交失败', null, $result['info']);
            }

        }
    }

    /**
 * 修改用户积分
 */
    public function changeScoreV2() {

//            if(!$this->isAdmin()){
//                $this->error('没有权限');
//            }
            $id = $this->_param('apply_id', '');
            $type = $this->_param('pass', '');
            $result = (new ScoreEditApplyLogic())->getInfo(['id'=>$id]);
            $apply_info = $result['info'];
            Db::startTrans();

            if($result['status']&&!empty($result['info'])){
                if($type == 'reject'){
                    $result = (new ScoreEditApplyLogic)->saveByID($id,['apply_status'=>2]);
                }else{
                    if($apply_info['score_type'] == 'plus'){
                        $result = (new AccountScoreLogic)->plusScore(AccountEnmu::USER, $apply_info['uid'], AccountScoreLogic::SCORE_TYPE_1, $apply_info['number'], '后台添加积分');
                    }else{
                        $result = (new AccountScoreLogic)->minusScore(AccountEnmu::USER, $apply_info['uid'], AccountScoreLogic::SCORE_TYPE_1, $apply_info['number'], '后台减少积分');
                    }
                    if($result['status']){
                        $result = (new ScoreEditApplyLogic)->saveByID($id,['apply_status'=>1]);
                        Db::commit();
                        $this->success('操作成功', null, $result['info']);
                    }else{
                        Db::rollback();
                        $this->error('积分修改失败', null, $result['info']);
                    }

                }
            }
            if($result['status']){
                Db::commit();
                $this->success('成功', null, $result['info']);
            }else{
                Db::rollback();
                $this->error('失败', null, $result['info']);
            }


    }

    /**
     * 修改用户积分申请
     */
    public function changeScoreApplyList() {
        if(IS_AJAX) {
//            if (!$this->isAdmin()) {
//                $this->error('没有权限');
//            }

            //查询未处理申请
            $p = $this->_param('p', 1);
            $size = $this->_param('size', 15);
            $page = ['curpage' => $p, 'size' => $size];
            $result = (new ScoreEditApplyLogic())->applyList($page);
            if ($result['status']) {
                $apply = $result['info'];
                $list = [];
                $VUserInfoLogic = (new VUserInfoLogic);
                foreach ($apply['list'] as $val) {
                    $result = $VUserInfoLogic->getInfo(['id' => $val['uid']]);
                    if (!$result['status']) $this->error('获取积分申请列表失败', null, $result['info']);
                    $val['nickname'] = $result['info']['nickname'];
                    $val['mobile'] = $result['info']['mobile'];
                    $list[] = $val;

                }
                $apply['list'] = $list;
                $this->success('获取申请列表成功', null, $apply);
            } else {
                $this->error('获取申请列表失败', null, $result['info']);
            }


        }
    }

}